import logging
import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from meiduo_mall.libs.captcha.captcha import captcha
from . import constants
from .serializer import ImageCodeCheckSerializer

logger = logging.getLogger('django')

class ImageCodeView(APIView):

    def get(self,request,image_code_id):
        # 生成验证码图片，获取随机文本和对应图片
        text,image = captcha.generate_captcha()
        # print(text)
        # print(image)

        # 将生成的验证码文本保存到redis
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex("img_%s"% image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)

        # 将生成的图片返回给前端
        return HttpResponse(image,content_type='image/jpg')


class SMSCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer

    def get(self,request,mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        sms_code = "%06d" % random.randint(0,999999)
        print(sms_code)

        redis_conn = get_redis_connection('verify_codes')
        # redis_conn.setex("sms_%s" % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        # redis_conn.setex("send_flag_%s" %mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        # 使用redis管道
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile,constants.SMS_CODE_REDIS_EXPIRES,sms_code)
        pl.setex("send_flag_%s" %mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()

        # try:
        #     ccp = CCP()
        #     expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        #     result = ccp.send_template_sms(mobile,[sms_code,expires],constants.SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     logger.error("发送验证码短信[异常][ mobile: %s, message: %s ]" % (mobile, e))
        #     return Response({'message':'failed'},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         logger.info("发送验证码短信[正常][ mobile: %s ]" % mobile)
        #         return Response({'message': 'OK'})
        #     else:
        #         print('发送短信验证码结果result：%s'%result)
        #         logger.warning("发送验证码短信[失败][ mobile: %s ]" % mobile)
        #         return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 使用celery完成异步任务
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60
        send_sms_code.delay(mobile,sms_code,expires,constants.SMS_CODE_TEMP_ID)
        return Response({'message':'OK'})



